package cn.b.training.baby_education_training.api;

import cn.b.training.baby_education_training.entity.FileInfo;
import cn.b.training.baby_education_training.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/api")
public class FileApi {
    @Autowired
    FileService fileService;
    @PostMapping("/upload")
    public ResponseEntity upload(MultipartFile file){
        String originalFileName = file.getOriginalFilename();
        String extName="";
        if(originalFileName.indexOf(".")>0){
            extName= originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        String serverFileName= UUID.randomUUID().toString()+extName;
        try {
            FileInfo fileInfo=fileService.uploadFile(file);
            return ResponseEntity.ok(fileInfo);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/upload2")
    public ResponseEntity upload2(MultipartFile file){
        String originalFileName = file.getOriginalFilename();
        String extName="";
        if(originalFileName.indexOf(".")>0){
            extName= originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        String serverFileName= UUID.randomUUID().toString()+extName;
        try {
            FileInfo fileInfo=fileService.uploadFile(file);
            return ResponseEntity.ok(fileInfo);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}
